const name = 'webgpu-editor';

const storage = {
  selected: '',

  autosave: true,

  'project/title': '',
  'project/editable': false,

  'project/renderer/antialias': true,
  'project/renderer/shadows': true,
  'project/renderer/shadowType': 1, // PCF
  'project/renderer/toneMapping': 0, // NoToneMapping
  'project/renderer/toneMappingExposure': 1,

  'settings/history': false,

  'settings/shortcuts/translate': 'w',
  'settings/shortcuts/rotate': 'e',
  'settings/shortcuts/scale': 'r',
  'settings/shortcuts/undo': 'z',
  'settings/shortcuts/redo': 'y',
  'settings/shortcuts/focus': 'f',
};

type Storage = typeof storage;
type StorageKey = keyof Storage;

if (window.localStorage[name] === undefined) {
  window.localStorage[name] = JSON.stringify(storage);
} else {
  const data: Storage = JSON.parse(window.localStorage[name]);
  for (const key in data) {
    const typeKey = key as StorageKey;
    setKey(typeKey, data[typeKey]);
  }
}

function setKey<T extends StorageKey>(key: T, value: Storage[T]) {
  storage[key] = value;
}

function getKey<T extends StorageKey>(key: T): Storage[T] {
  return storage[key];
}

const REGEX_HH_MM_SS = /\d\d:\d\d:\d\d/; // Matches HH:MM:SS

export const config = {
  getKey,

  setKey: <T extends StorageKey>(key: T, value: Storage[T]) => {
    setKey(key, value);
    window.localStorage[name] = JSON.stringify(storage);
    console.log(`[${REGEX_HH_MM_SS.exec(new Date().toDateString())?.[0]}]`, 'Saved config to LocalStorage.');
  },

  clear: () => {
    delete window.localStorage[name];
  },
};
